package promotion

import (
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/flaravel/quanlaolao/pkg/model"
	"github.com/flaravel/quanlaolao/pkg/pagination"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"net/http"
)

func GetAll(r *http.Request, perPage int) ([]GroupPromotion, pagination.ViewData, error) {

	db := model.DB.Model(&GroupPromotion{}).Order("created_at desc")
	_pager := pagination.New(r,  db, route.Name2URL("cps.index"), perPage)

	viewData := _pager.Paging()

	var cps []GroupPromotion
	_ = _pager.Results(&cps)

	return cps, viewData, nil
}

func (group *GroupPromotion) Create() (err error) {
	if err = model.DB.Create(&group).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}

func (group *GroupContent) Create() (err error) {
	if err = model.DB.Create(&group).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}

func Get(idstr string) (GroupPromotion, error) {
	var cps GroupPromotion
	id := types.StringToInt(idstr)
	if err := model.DB.Preload("GroupAvatars").Preload("GroupContents").First(&cps, id).Error; err != nil {
		return cps, err
	}

	return cps, nil
}

func (group *GroupAvatar) AvatarCreate() (err error) {
	if err = model.DB.Create(&group).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}

func GetList() ([]GroupPromotion, error) {
	var cps []GroupPromotion
	if err := model.DB.Find(&cps).Error; err != nil {
		return cps, err
	}

	return cps, nil
}

func (group *GroupPromotion) Delete() (rowsAffected int64, err error) {
	result := model.DB.Delete(&group)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}
func (group *GroupPromotion) Update() (rowsAffected int64, err error) {
	result := model.DB.Save(&group)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}